'use strict';
const db = uniCloud.database();
const dbCmd = db.command ;
const $ = db.command.aggregate ;
const dbo = db.collection("opendb-news-articles");
const cate = db.collection("opendb-news-categories");
module.exports = {
	
	save : async function(e){
		var data = this.getModel();
		
		if (!data._id) {
			data.last_modify_date=data.publish_date = Date.now();
			// data.mode=1			
			await dbo.add(data);
			return this.ok();
		}
		var roleInDb = this.findFirst(await dbo.doc(data._id).get());
		if (null == roleInDb) {
			return this.fail("信息不存在");
		}		
		data.last_modify_date= Date.now();
		await this.updateById(dbo , data);
		return this.ok();
	},
	info : async function(e){
		var id = this.params.id ;		
		if (!id) {
			return {};
		}
		var data = this.findFirst( await dbo.doc(id).get() );
		return { data };
	},
	delete : async function(e){
		var id = this.params.id ;
		await dbo.doc(id).remove();
		return this.ok();
	},
	list : async function(e){
		var {pageNumber , pageSize,where } = this.params ;
		
		var page = await this.paginate({
			pageNumber , pageSize ,
			collection : dbo ,
			where:where||{},
			eq : ["category_id","user_id","article_status","is_essence","is_sticky"],
			range : ["publish_date,createTimeStart,createTimeEnd"],
			like : ["title","excerpt","content"],
			orderBy : "is_sticky desc,publish_date desc" 
		});
		
		var dataInDB = await cate.field({
			"name" : 1 ,
			"_id":1,			
			"create_date":1		
		}).orderBy("create_date","asc").get() ;
		var catelist = this.find( dataInDB );
		
		var list = page.list ;
			
			list.forEach(item=>{
				
					let category=catelist.filter(e=>e._id == item.category_id)
					if(category && category.length>0)
						item.category_id=category[0].name||'';
				//item.publish_date = this.DateKit.toStr( item.publish_date ,'seconds');
			});
		
		return {page};
	}
	
}